// pages/commodity/commodityInfo/commodityInfo.js
const app = getApp()
import config from '../../../utils/config.js';
import util from '../../../utils/util.js';
import Toast from '../../../vant/toast/toast';
let Charts = require('../../../utils/wxcharts-min.js');
import {
  comModel
} from '../../../models/com';
const com = new comModel();
import {
  coreModel
} from '../../../models/core';
const core = new coreModel();

Page({

  /**
   * 页面的初始数据
   */
  data: {
    config:config,
    nvabarData: {
      showCapsule: 1, //是否显示左上角图标   1表示显示    0表示不显示
      title: '商品详情',
      //  导航栏 中间的标题
    },
    roleType: '', // 角色类别 1食堂人员,2档口人员
    stallPriceStatus: '', // 是否显示价格 1显示
    
    productId:'',
    addt:2,      // 是否显示加入清单按钮 1 是 2 否

    indicatorDots: false,
    autoplay: false,
    interval: 5000,
    duration: 1000,
    imgList: [], // 轮播图片列表
    current: 1, // 轮播index

    detail:{},
    annexFiles:[],

    // specsShow:false, // 规格
    // goodVoList:[],   //规格列表
    show: false, // 规格popup
    productSpecVoList: '', // 规格列表
    selectP: '', // 选择的规格
    clickfindex: '',
    value: 1, // 购买数量
    goods: '', // 选中商品详情

    chartFlag: false,
    legendData: '',
    canvasTemImg: '',
    colorList: ['#3FDA93','#2FBEE4','#F18C58','#c23531','#2f4554', '#61a0a8', '#d48265', '#91c7ae','#749f83',  '#ca8622', '#bda29a','#6e7074', '#546570', '#c4ccd3']
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
      var userInfo = wx.getStorageSync('userInfo')
      var productId = options.productId;
      var addt = options.addt;
      console.log(addt);
      this.setData({
        roleType: userInfo.roleType,
        productId:productId,
        addt:userInfo.stallId?1:2 // 验证当前用户是否已分配档口
      })
      core.apiInfoCantee({}, res => {
        this.setData({
          stallPriceStatus: res.stallPriceStatus
        })
      })
      this.getDetail();
      this.getStatistics()
  },
  getStatistics(){
    com.listProductUpdatePriceRecord({
      productId: this.data.productId
    }, res => {
      if(res.data){
        if(res.data[0].goodPriceWithTimeVoList.length==0){
          this.setData({
            chartFlag: true
          })
          
          return
        }else{
          this.data.chartFlag = false
          
        }
        var xAxisData = []
        var seriesData = []
        for(var i=0;i<res.data.length;i++){
          var a = {
            name: res.data[i].skuName,
            color: this.data.colorList[i<14?i:(i%14)],
            data: []
          }
          for(var k=0;k<res.data[i].goodPriceWithTimeVoList.length;k++){
            a.data.push(res.data[i].goodPriceWithTimeVoList[k].price)
          }
          seriesData.push(a)
        }
        for(var j=0;j<res.data[0].goodPriceWithTimeVoList.length;j++){
          xAxisData.push(res.data[0].goodPriceWithTimeVoList[j].time)
        }
        this.setData({
          legendData: seriesData,
          canvasTemImg: ''
        })
        console.log(xAxisData,seriesData)
        this.getChart(xAxisData,seriesData) 

      }
    })
  },
  getChart(xAxisData,seriesData){
    var _this = this
    _this.setData({
      chartFlag: false
    })
    var chart = new Charts({
      canvasId: 'canvas',
      type: 'column',
      categories: xAxisData,
      series: seriesData,
      yAxis: {
        min: 0
      //   format: function (val) {
      //     return val
      //   }
      },
      width: 340,
      height: 250,
      legend: false,
    });
    // 监听画笔画完
    chart.addEventListener('renderComplete', () => {
      _this.draw()
    });
  },
  
  draw(){
    var _this = this
    wx.canvasToTempFilePath({
      canvasId:'canvas',
      quality: 1,
      success: res => {
        _this.setData({
          canvasTemImg: res.tempFilePath
        })
      },
      fail: res => {
        console.log(res)
      }
    },this)

  },


  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  // 轮播图切换
  swiperChange(e) { 
    this.setData({
      current: e.detail.current + 1
    })
  },

  // 查询商品详情
  getDetail() { 
    com.productDetail({
      productId: this.data.productId,
    }, res => {
      var img = res.smallPic
      var imgList = JSON.parse(img) // 图片
      console.log(imgList);
      var annexFiles = JSON.parse(res.annexFiles); //附件
      res.content = util.formatRichText(res.content)
      var productSpecVoList = res.productSpecVoList // 商品规格
      this.emptySpec(productSpecVoList, res.goodVoList)
      var selectP = []
      for (var i = 0; i < productSpecVoList.length; i++) {
        var p = {
          propertyId: '',
          propertyValueId: ''
        }
        selectP.push(p)
      }
      var stockCount = 0
      if (res.goodVoList.length == 1) {
        this.setData({
          goods: res.goodVoList[0],
          value: res.goodCountMap[res.goodVoList[0].id]
        })
        
        // 取数量
        // var goods = this.data.goods;   
        // var goodCountMap = detail.goodCountMap;
        // console.log(goodCountMap[goods.id]);

        for (var j=0;j<res.goodVoList[0].goodSpecVoList.length;j++){
          selectP[j].propertyValueId = res.goodVoList[0].goodSpecVoList[j].specValueId
        }
      }
      for (var k=0;k<res.goodVoList.length;k++){
        stockCount += res.goodVoList[k].stockCount
      }

      this.setData({
        imgList: imgList,
        detail: res,
        selectP: selectP,
        stockCount: stockCount,
        goodVoList:res.goodVoList
      })

      this.updateGate(annexFiles);

      // if(res.goodVoList.length == 1){
      //   this.ifSelectNum(); // 数量
      // }
    })
  }, 

  // 规格
  emptySpec(productSpecVoList, goodVoList) { // 判断库存为空的规格
    for (var i = 0; i < productSpecVoList.length; i++) {
      for (var j = 0; j < productSpecVoList[i].productSpecValueList.length; j++) {
        var empty = this.returnEmpty(productSpecVoList[i].productSpecValueList[j],goodVoList)
        if (empty && this.data.clickfindex !== i){
          productSpecVoList[i].productSpecValueList[j].specValueImage = '00'
        } else {
          productSpecVoList[i].productSpecValueList[j].specValueImage = ''

        }
      }

    }
    this.setData({
      productSpecVoList: productSpecVoList
    })
  },
  returnEmpty(productSpec,goodVoList) {
    var empty = true
    var allEmpty = true
    for (var i = 0; i < goodVoList.length; i++) {
      var t = false
      for (var j = 0; j < goodVoList[i].goodSpecVoList.length; j++) {
        if (productSpec.id == goodVoList[i].goodSpecVoList[j].specValueId) {
          t = true
          allEmpty = false
          break
        }
      }
      if(t){
        if (goodVoList[i].stockCount != 0) {
          empty = false
        } else if (goodVoList[i].stockCount == 0) {
          if (this.data.clickfindex !== '') {
            empty = true
            break
          }
        }
      } else if (i == goodVoList.length - 1 && allEmpty) {
        empty = false
      }
    }
    return empty
  },

  // 选择规格
  onSku(e) { 
    var findex = e.currentTarget.dataset.findex
    var sindex = e.currentTarget.dataset.sindex
    var propertyList = this.data.productSpecVoList
    var selectP = this.data.selectP
    if (selectP[findex].propertyValueId != propertyList[findex].productSpecValueList[sindex].id) {
      selectP[findex].propertyId = propertyList[findex].id
      selectP[findex].propertyValueId = propertyList[findex].productSpecValueList[sindex].id
      this.setData({
        selectP: selectP,
        clickfindex: Number(findex)
      })
      this.getGoddsId(findex, sindex)
    }
  },
  getGoddsId(findex, sindex) {
    var productSpecVoList = this.data.productSpecVoList
    for (var k = 0; k < productSpecVoList.length; k++) {
      if (findex === k) {
        continue
      }
      for (var l = 0; l < productSpecVoList[k].productSpecValueList.length; l++) {
        productSpecVoList[k].productSpecValueList[l].specValueImage = ''
      }
    }
    var goodVoList = this.data.detail.goodVoList
    var selectP = this.data.selectP
    var g = [];

    // 初始化选中规格
    this.setData({
      goods: '',
    })

    for (var i = 0; i < goodVoList.length; i++) {
      var t = false
      var pFlag = this.check(goodVoList[i]) // 判断选中的所有规格
      if (pFlag) {
        this.setData({
          goods: goodVoList[i], // 选中商品
          value: this.data.detail.goodCountMap[goodVoList[i].id] // 选择商品数量
        })
      }
      // for (var j = 0; j < goodVoList[i].goodSpecVoList.length; j++) {
      for (var j = 0; j < selectP.length; j++) {
        // if (productSpecVoList[findex].productSpecValueList[sindex].id == goodVoList[i].goodSpecVoList[j].specValueId) {
        if (selectP[j].propertyValueId && selectP[j].propertyValueId == goodVoList[i].goodSpecVoList[j].specValueId) {
          t = true
          break
        }
      }

      if (t) {
        g.push(goodVoList[i])
      }
    }
    if (productSpecVoList.length > 1) {
      this.emptySpec(productSpecVoList, g)

    }
  },
  check(item){
    var pFlag = true
    for (var j = 0; j < item.goodSpecVoList.length; j++) {
      if (item.goodSpecVoList[j].specValueId == this.data.selectP[j].propertyValueId) {
        pFlag = pFlag&&true
      } else {
        pFlag = pFlag&&false
      }
    }
    return pFlag
  },

  onValue(e) { // 商品数量
    this.setData({
      value: e.detail
    })
  },

  // 加入报单
  onDeclara: util.throttle(function (e) { // 立即购买
    var flag = false
    if (!this.data.show) {
      this.setData({
        show: true
      })
    } else {
      for (var i = 0; i < this.data.selectP.length; i++) {
        if (!this.data.selectP[i].propertyValueId) {
          util.msg('请选择规格');
          flag = true
          break;
        }
      }
      if (!flag) {
        
        com.apiAddProductCar({
          goodsId:this.data.goods.id,
          goodsCount: this.data.value?this.data.value:1,
        }, res => {    
          Toast.success('操作成功');

          // 如果上一页是档口报单页面则刷新数据
          let pages = getCurrentPages();
          let prevPage = pages[pages.length - 2];
          if(prevPage.route=='pages/coreAdmin/gateDeclaration/gateDeclaration'){
            prevPage.setData({
              ifRefresh: true,
            })
          }

          setTimeout(function () {
            wx.navigateBack({
              delta: 1,
            })
          }, 1000);
        })
      }
    }
  }),

  // 数据编排
  updateGate(annexFiles){
    var newGate = [];
    if(annexFiles){
      for(var i=0;i<annexFiles.length;i++){
        var list ={
          name: annexFiles[i].filename,
          url:annexFiles[i].file,
          color: '#F56545'
        };
        newGate.push(list)
    }
    }
      
      this.setData({
        annexFiles:newGate
      })
      console.log(this.data.annexFiles);
  },

  // 选择附件
  onSelecFile(){
    this.setData({
      gateShow: true
    })
  },

  gateSelect(event){
    var url = event.detail.url
    this.seeFile(url)
    this.setData({
      gateShow: false,
    })
  },

  gateClose(){
    this.setData({
      gateShow: false
    })
  },

  gateCancel(){
    this.setData({
      gateShow: false
    })
  },

  // 在线预览文件
  seeFile(openUrl){
    
    var suffixStr = util.suffixStr(openUrl)
    suffixStr = suffixStr.split('&')[0]
    if(!suffixStr){
      return
    }
    if(suffixStr !="pdf"){
      wx.previewImage({
        current: config.projectUrl+openUrl, // 当前显示图片的http链接
        urls: [config.projectUrl+openUrl]
      })
      return
    }
    wx.showLoading({
      title: '请稍等',
      icon: 'loading',
      mask: true
    })
    wx.downloadFile({
      url: config.projectUrl+openUrl,
      success: function (res) {
        const filePath = res.tempFilePath
        console.log(filePath);
        wx.openDocument({
          filePath: filePath,
          fileType:'pdf',
          showMenu:true,
          success: function (res) {
            wx.hideLoading();
            console.log('打开文档成功')
          },
          fail:function(res){
            wx.hideLoading();
            console.log(res)
          }
        })
        
      },
      fail:function(res){
        wx.hideLoading();
        console.log(res)
      }
    })
  },

  // 关闭
  onClose(){
    this.setData({
      show:false
    })
  },

  // 最后加入报单
  endDeclara(){
    com.apiAddProductCar({
      productId: this.data.productId,
    }, res => {
      
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    let pages = getCurrentPages();
    let prevPage = pages[pages.length - 2];
    // 设置上一页不在onShow的时候重新加载数据，在本页设置刷新列表
    prevPage.data.fLoad = true
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})